package cn.chiship.framework.upms.biz.system.controller;


import cn.chiship.framework.upms.biz.system.entity.UpmsHelpContent;
import cn.chiship.framework.upms.biz.system.pojo.vo.ContentUnionAllCategoryVo;
import cn.chiship.sdk.core.annotation.Authorization;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.framework.base.BaseController;
import cn.chiship.sdk.framework.pojo.vo.PageVo;
import cn.chiship.sdk.framework.base.BaseService;

import javax.annotation.Resource;
import javax.validation.Valid;

import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.framework.common.annotation.SystemOptionAnnotation;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.framework.common.enums.BusinessTypeEnum;
import cn.chiship.framework.upms.biz.system.service.UpmsHelpContentService;
import cn.chiship.framework.upms.biz.system.entity.UpmsHelpContentExample;
import cn.chiship.framework.upms.biz.system.pojo.dto.UpmsHelpContentDto;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 帮助文档控制层
 * 2021/9/30
 *
 * @author lijian
 */
@RestController
@RequestMapping("/helpContent")
@Api(tags = "帮助文档")
public class UpmsHelpContentController extends BaseController<UpmsHelpContent, UpmsHelpContentExample> {

    @Resource
    private UpmsHelpContentService upmsHelpContentService;

    @Override
    public BaseService getService() {
        return upmsHelpContentService;
    }

    /**
     * 帮助文档分页
     */
    @ApiOperation(value = "帮助文档分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页条数", defaultValue = "10",  dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序方式", defaultValue = "-gmtModified", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "title", value = "文档标题", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "所属分类", dataTypeClass = String.class, paramType = "query"),

    })
    @GetMapping(value = "page")
    @Authorization
    public ResponseEntity<BaseResult> page(@RequestParam(required = false, defaultValue = "", value = "title") String title,
                                           @RequestParam(required = false, defaultValue = "", value = "categoryId") String categoryId) {
        UpmsHelpContentExample upmsHelpContentExample = new UpmsHelpContentExample();

        UpmsHelpContentExample.Criteria criteria = upmsHelpContentExample.createCriteria();
        criteria.andIsDeletedEqualTo(BaseConstants.NO);
        if (!StringUtil.isNullOrEmpty(title)) {
            criteria.andTitleLike("%" + title + "%");
        }
        if (!StringUtil.isNullOrEmpty(categoryId)) {
            criteria.andCategoryIdEqualTo(categoryId);
        }

        PageVo pageVo = super.page(upmsHelpContentExample);
        return super.responseEntity(BaseResult.ok(pageVo));
    }

    /**
     * 保存文档
     */
    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_SAVE, describe = "保存文档")
    @ApiOperation(value = "保存文档")
    @PostMapping("save")
    @Authorization
    public ResponseEntity<BaseResult> save(@RequestBody @Valid UpmsHelpContentDto upmsHelpContentDto) {
        UpmsHelpContent upmsHelpContent = new UpmsHelpContent();
        BeanUtils.copyProperties(upmsHelpContentDto, upmsHelpContent);
        return super.responseEntity(super.save(upmsHelpContent));
    }

    /**
     * 更新文档
     */
    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE, describe = "更新文档")
    @ApiOperation(value = "更新文档")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path"),
    })
    @PostMapping(value = "update/{id}")
    @Authorization
    public ResponseEntity<BaseResult> update(@PathVariable("id") String id, @RequestBody @Valid UpmsHelpContentDto upmsHelpContentDto) {
        UpmsHelpContent upmsHelpContent = new UpmsHelpContent();
        BeanUtils.copyProperties(upmsHelpContentDto, upmsHelpContent);
        return super.responseEntity(super.update(id, upmsHelpContent));
    }

    /**
     * 删除文档
     */
    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "删除文档")
    @ApiOperation(value = "删除文档")
    @PostMapping(value = "remove")
    @Authorization
    public ResponseEntity<BaseResult> remove(@RequestBody @Valid List<String> ids) {
        UpmsHelpContentExample upmsHelpContentExample = new UpmsHelpContentExample();
        upmsHelpContentExample.createCriteria().andIdIn(ids);
        return super.responseEntity(super.remove(upmsHelpContentExample));
    }


    @ApiOperation(value = "根据父级元素获得文档目录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pid", value = "父级主键", required = true, dataTypeClass = String.class, paramType = "query"),
    })
    @GetMapping(value = "/contentUnionAllCategoryByPid")
    public ResponseEntity<BaseResult> selectContentUnionAllCategoryByPid(@RequestParam(value = "pid") String pid) {
        HashMap<String, Object> map = Maps.newHashMapWithExpectedSize(7);
        List<ContentUnionAllCategoryVo> contentUnionAllCategoryVos = upmsHelpContentService.selectContentUnionAllCategory(map);
        return super.responseEntity(BaseResult.ok(assemblyContentUnionAllCategoryTreeTree(pid, contentUnionAllCategoryVos)));
    }

    private List<JSONObject> assemblyContentUnionAllCategoryTreeTree(String pid, List<ContentUnionAllCategoryVo> contentUnionAllCategoryVos) {
        List<JSONObject> treeVos = new ArrayList<>();
        for (ContentUnionAllCategoryVo contentUnionAllCategoryVo : contentUnionAllCategoryVos) {
            List<String> pids = Arrays.asList(contentUnionAllCategoryVo.getPid().split(";"));
            if (pids.contains(pid)) {
                treeVos.add(JSON.parseObject(JSON.toJSONString(contentUnionAllCategoryVo)));
            }
        }
        for (JSONObject treeVo : treeVos) {
            List<JSONObject> children = assemblyContentUnionAllCategoryTreeTree(treeVo.getString("id"), contentUnionAllCategoryVos);
            if (!children.isEmpty()) {
                treeVo.put("children", children);
            }
        }
        return treeVos;
    }

}
